// 导入路有对象构造函数
const Router = require("koa-router");
const http = require("../utils/http.js");
// 创建路由导航
const router = new Router({
    prefix: "/cart"
});

// 自定义配置路有对象

// 用户的购物车记录
router.get("/list", async (ctx, next) => {
    //async 总是会返回一个成功的Promise 相当于return new Promise.resolve([1,2,3,4]);
    const openid = ctx.state.openid;
    const sql = 'select T1.id,T1.pid,T1.count,T2.name,T2.avatar,T2.price,T2.brief from `dt_cart` T1,`dt_product` T2 where T1.pid = T2.id and T1.openid = ?;';
    let results = await http(sql, [openid]);
    return Promise.resolve(results);
});
// 获取指定购物车id的相关信息
router.post("/list_ids", async (ctx, next) => {
    const {
        ids
    } = ctx.request.body;
    var sql = 'select T1.id,T1.pid,T1.count,T2.name,T2.avatar,T2.price,T2.brief from (select * from `dt_cart` where `id` in (?)) T1 inner join `dt_product` T2 on T1.pid = T2.id;';
    const results = await http(sql, [ids]);
    return Promise.resolve(results);
});
// 向购物车添加商品
router.post("/add_product", async (ctx, next) => {
    let openid = ctx.state.openid;
    let {
        pid,
        count,
        price
    } = ctx.request.body;
    console.log("添加到购物车:", ctx.request.body);
    // 执行添加到数据库操作
    const results = await http('call p_addProductToCart(?,?,?,?)', [openid, pid, count, price]);

    console.log("添加成功的测试数据:", results);
    if (results[0][0].result === "") {
        return Promise.resolve();
    } else
        return Promise.reject(results[0][0].result);
});

router.get("/increase/:id", async (ctx, next) => {
    const id = parseInt(ctx.params.id);
    const sql = 'update `dt_cart` set `count` = `count` + 1 where `id` = ?;';
    const results = await http(sql, [id]);
    if (results.affectedRows === 1)
        return Promise.resolve();
    else
        return Promise.reject('数量增加失败..');
});
router.get("/deincrease/:id", async (ctx, next) => {
    const id = parseInt(ctx.params.id);
    const sql = 'update `dt_cart` set `count` = `count` - 1 where `id` = ?;';
    const results = await http(sql, [id]);
    if (results.affectedRows === 1)
        return Promise.resolve();
    else
        return Promise.reject('数量减少失败..');
})
// 批量删除指定用户的购物记录
router.post("/batch_remove", async (ctx, next) => {
    const {
        ids
    } = ctx.request.body;
    const sql = 'delete from `dt_cart` where `id` in (?);';
    const results = await http(sql, [ids]);
    if (results.affectedRows === ids.length)
        return Promise.resolve();
    else
        return Promise.reject('从购物车中删除商品失败..');
});
// 获取当前登录用户购物车中所有的购物记录总数量
router.get("/total", async (ctx, next) => {
    const openid = ctx.state.openid;
    const sql = 'select sum(`count`) as total from `dt_cart` where `openid` = ?;';
    const results = await http(sql, [openid]);
    return Promise.resolve(results[0].total || 0);
})

module.exports = router.routes();